package com.youpai.platform.user.service.service.impl;

import com.youpai.platform.common.enums.ProcessCodeEnum;
import com.youpai.platform.common.exceptions.BaseBizException;
import com.youpai.platform.common.util.DeviceContext;
import com.youpai.platform.user.service.entity.po.VersionInfoPO;
import com.youpai.platform.user.service.mapper.VersionInfoMapper;
import com.youpai.platform.user.service.service.VersionInfoService;
import com.youpai.platform.user.web.entity.req.VersionInfoReq;
import com.youpai.platform.user.web.entity.resp.VersionInfoResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @time: 2022/11/12
 * @author: lizhoujie
 * @description: 版本信息service实现类
 */
@Slf4j
@Service
public class VersionInfoServiceImpl implements VersionInfoService {

    @Resource
    private VersionInfoMapper versionInfoMapper;

    @Override
    public VersionInfoResp getVersionInfo(VersionInfoReq req){
        VersionInfoPO versionInfo = versionInfoMapper.getForceUpdate(DeviceContext.getAppId(), req.getVersionNumber(),req.getPlatform());
        if(versionInfo == null){
            log.error("未获取到版本信息!");
            throw new BaseBizException(ProcessCodeEnum.VERSION_NOT_EXIST);
        }
        Integer forceUpdate = versionInfo.getForceUpdate();
        VersionInfoResp versionInfoResp = new VersionInfoResp();
        VersionInfoPO linkAndContent = versionInfoMapper.getNewLinkAndContent(req.getPlatform());
        if(linkAndContent == null){
            log.error("未获取到版本信息!");
            throw new BaseBizException(ProcessCodeEnum.VERSION_NOT_EXIST);
        }
        if (forceUpdate == 0 || req.getVersionNumber().equals(linkAndContent.getVersionNumber())) {
            versionInfoResp.setForceUpdate(0);
        } else if (forceUpdate == 2) {
            versionInfoResp.setForceUpdate(2);
        } else {
            versionInfoResp.setForceUpdate(forceUpdate)
                    .setDownloadLink(linkAndContent.getDownloadLink())
                    .setUpdateContent(linkAndContent.getUpdateContent())
                    .setPlatformSchema(linkAndContent.getPlatformSchema());
        }
        return versionInfoResp;
    }
}